package cn.ludi.filter;

import cn.ludi.context.BaseContext;
import cn.ludi.entity.LoginUser;
import cn.ludi.mapper.UserSessionMapper;
import cn.ludi.utils.JwtUtil;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private UserSessionMapper userSessionMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //1、从请求头中获取令牌
        String token = request.getHeader("token");

        log.info("jwt校验:{}", token);
        Claims claims = JwtUtil.parseJWT("ludi", token);
        Long userId = Long.valueOf(claims.get("userId").toString());
        BaseContext.setCurrentId(userId);
        log.info("当前用户id：{}", userId);
        //3、通过，放行

        //从session表中获取loginUser对象
        LoginUser loginUser = JSONObject.parseObject(userSessionMapper.getByUserId(userId).getUserInfo(),LoginUser.class);

        if(null == loginUser){
            throw new RuntimeException("用户信息不存在");
        }
        //存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }
}
